package pers.vic.upload.business.service;

import cn.xuqiudong.common.base.tool.Tools;
import cn.xuqiudong.common.util.CnToSpellUtils;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import pers.vic.upload.constant.FinalFiledParams;
import pers.vic.upload.utils.SessionHelper;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;

/**
 * 描述: 附件操作
 * @author Vic.xu
 * @date 2022-07-22 11:11
 */
@Service
public class AttachmentService {

    @Resource
    private JdbcTemplate jdbcTemplate;

    private static Logger logger = LoggerFactory.getLogger(AttachmentService.class);




    /**
     * 新增附件
     * @param file
     * @return uuid for  attachment
     */
    public String insert(File file){
        String uuid = Tools.randomUuid();
        String userId = SessionHelper.userId();
        String originalFileName = StringUtils.substringBeforeLast(file.getName(), ".");
        String ext = StringUtils.substringAfterLast(file.getName(), ".");
        String newFileName = Tools.randomUuid();
        File newFile;
        try {
            newFile = moveFile(file, newFileName + "." + ext);
        } catch (IOException e) {
            e.printStackTrace();
            throw  new RuntimeException("移动文件"+file.getAbsolutePath()+"出错: " +  e.getMessage());
        }
        long size = file.length();
        String path = newFile.getAbsolutePath();
        String sql = "insert into T_STL_S_ATTACHMENT" +
                "(id, CREATE_DATE,CREATE_USER_ID,Last_Update_Date, Last_Update_User_Id,  Enable_Flag, FILE_NAME,FILE_PATH, FILE_SIZE,Original_File_Name, FK_OWNER_ID, ext)" +
                " values(?, sysdate, ?, sysdate, ?, 1, ?, ?, ?,?, ?, ? ) ";
        Object[] args = new Object[]{uuid, userId,userId,  newFileName, path, size, originalFileName, userId, ext};
        jdbcTemplate.update(sql, args);
        return uuid;
    }

    /**
     * 移动文件
     * @param file 原文件
     * @return 新文件位置
     * @throws IOException ex
     */
    private File moveFile(File file, String newFileName) throws IOException {
        String replacement = File.separator + FinalFiledParams.TEMPORARY_FOLDER + File.separator;
        String parent = file.getParent().replace(replacement, File.separator);
        //String cnFileName = CnToSpellUtils.getFullSpell(file.getName());
        //// 去掉一些特殊的字符
        //cnFileName = cnFileName.replaceAll("[/?:@=&]", "");
        File newFile = new File(parent, newFileName);
        FileUtils.moveFile(file, newFile);
        logger.info("成功移动文件{}到{}", file.getAbsolutePath(), newFile.getAbsolutePath());
        return newFile;
    }


    /**
     * 新增附件关系
     * @param table 关系表
     * @param businessColumn businessColumn name
     * @param businessId businessId
     * @param attachmentColumn attachmentColumn name
     * @param attachmentId attachmentId
     */
    public void insertRelation(String table, String businessColumn, String businessId, String attachmentColumn, String attachmentId){
        String sql = " insert into " + table  + " (" + businessColumn + ", " + attachmentColumn + ") values (?, ?)";
        jdbcTemplate.update(sql, businessId, attachmentId);
    }


    /**
     * 文件是否已上传过
     * @param fileName fileName
     * @return boolean
     */
    public boolean existFileName(String fileName){
        String sql = "select count(1) from T_STL_S_ATTACHMENT a  where a.original_file_name = ? ";
        return jdbcTemplate.queryForObject(sql, Integer.class, fileName) > 0;
    }

    public static void main(String[] args) {
        String name = "/share1/app/uploadfile/cpleaseyx/socket-upload/tmp/admin/warrant/1107001_COR_20201003_20221001.pdf";
        File file = new File(name);
        String replacement = File.separator + FinalFiledParams.TEMPORARY_FOLDER + File.separator;
        String parent = file.getParent().replace(replacement, File.separator);
        //String cnFileName = CnToSpellUtils.getFullSpell(file.getName());
        //// 去掉一些特殊的字符
        //cnFileName = cnFileName.replaceAll("[/?:@=&]", "");
        File newFile = new File(parent, "123.pdf");
        System.out.println(newFile.getAbsolutePath());

    }
}
